package com.sso.server.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sso.server.entity.Users;
import com.sso.server.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;

/**
 * @author songyouchao
 * @ClassName SystemUserDetailService.java
 * @Description
 * @createTime 2021年08月15日
 */
@Service("userDetailService")
public class SystemUserDetailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        Users users = usersMapper.selectOne(wrapper);
        String role ="";
        if(StringUtils.equals(users.getUsername(),"admin")){
            role = "ROLE_admin,ROLE_data";
        }else{
            role = "ROLE_data";
        }
        if(null == users){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(role);
        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }
}
